#pragma once
#include <thread>
#include <signal.h>
#include "TcpServer.hpp"
// #include "Protocol.hpp"
#include "Task.hpp"
#include "ThreadPool.hpp"

#define PORT 8081

class HttpServer
{
  public:
    HttpServer(int port = PORT)
        : _port(port)
        , _stop(false)
    {}
    void InitServer()
    {
        //忽略信号SIGPIPE，否则写入时可能崩溃
        signal(SIGPIPE, SIG_IGN);
        // _tcp_server = TcpServer::getinstance(_port);
    }
    void Loop()
    {
        LOG(INFO, "Loop begin");
        // int listen_sock = _tcp_server->Sock();
        TcpServer *tcp_server_pointer = TcpServer::getinstance(_port);
        while(!_stop)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sock = accept(tcp_server_pointer->Sock(), (sockaddr*)&peer, &len);
            if(sock < 0)
            {
                continue;
            }
            LOG(INFO, "Get a new link");
            Task task(sock);
            // _thread_pool.PushTask(task);
            ThreadPool::getinstance()->PushTask(task);
            // task.ProcessOn();

            // int *_sock = new int(sock); //临时方案：避免因为值拷贝，线程对sock修改失效
            // pthread_t tid;
            // pthread_create(&tid, nullptr, Entrance::HandlerRequest, _sock);
            // pthread_detach(tid);
            // std::thread t(Entrance::HandlerRequest, _sock);
            // t.detach();
            // if(t.joinable())
            // {
            //     t.join();
            // }
        }
    }
    ~HttpServer()
    {}

  private:
    int _port;
    // TcpServer* _tcp_server;
    bool _stop;
    // ThreadPool _thread_pool;
};
